package com.droiddata;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SQLiteTransactionManager implements ISQLiteTransactionManager {
	private SQLiteOpenHelper dbHelper;
	private TransactionStatus status;
	private SQLiteDatabase db;
	private int frameCount = 0;

	public SQLiteTransactionManager(SQLiteOpenHelper dbHelper) {
		this.dbHelper = dbHelper;
		this.status = new TransactionStatus(db == null || !db.isOpen());
	}

	public ITransactionStatus getTransactionStatus() {
		return status;
	}

	public SQLiteDatabase beginTransaction() {
		if (db == null || !db.isOpen()) {
			try {
				db = dbHelper.getReadableDatabase();
				db.beginTransaction();
			}
			catch(SQLiteException e) {
				Log.e("Error opening database", e.getMessage());
				e.printStackTrace();
			}
			catch(IllegalStateException e) {
				Log.e("Unable to start transaction", e.getMessage());
				e.printStackTrace();
			}
		}
		frameCount++;		
		return db;
	}

	public void endTransaction() {
		if (--frameCount == 0) {
			// FIXME why would the database ever be closed?
			if(!db.isOpen())
				return;
			if (!status.isRollbackOnly())
				db.setTransactionSuccessful();
			db.endTransaction();
			db.close();
		}
	}
}